using System;
using System.Runtime.InteropServices;
using System.Windows;
using WPFTemplateLib.Utilities;

namespace WPFTemplateLib.WpfHelpers
{
	/// <summary>
	/// WPF 屏幕帮助类
	/// https://www.codeleading.com/article/15213064956/
	/// </summary>
	public class ScreenHelper
	{
		/// <summary>
		/// 获取缩放比例
		/// </summary>
		/// <returns></returns>
		public static double GetScalingRatio()
		{
			var logicalHeight = GetLogicalHeight();
			var actualHeight = GetActualHeight();

			if(logicalHeight > 0 && actualHeight > 0)
			{
				return logicalHeight / actualHeight;
			}

			return 1;
		}

		private static double GetActualHeight()
		{
			return SystemParameters.PrimaryScreenHeight;
		}

		private static double GetLogicalHeight()
		{
			var logicalHeight = 0.0;

			WindowsMonitorAPI.MonitorEnumProc proc = (m, h, lm, lp) =>
			{
				WindowsMonitorAPI.MONITORINFOEX info = new WindowsMonitorAPI.MONITORINFOEX();
				WindowsMonitorAPI.GetMonitorInfo(new HandleRef(null, m), info);

				//是否为主屏
				if((info.dwFlags & 0x00000001) != 0)
				{
					logicalHeight = info.rcMonitor.bottom - info.rcMonitor.top;
				}

				return true;
			};

			WindowsMonitorAPI.EnumDisplayMonitors(WindowsMonitorAPI.NullHandleRef, null, proc, IntPtr.Zero);

			return logicalHeight;
		}
	}
}
